from django.conf import settings
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer
from rest_framework import mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users import serializers
from users.models import User
from users.serializers import EmailSerializer, AddBrowseHistorySerializer


class TestView(View):
    def get(self, request):
        return render(request, 'test.html')


class TestView2(APIView):
    def get(self, request):
        return Response({'message': 'get请求'})

    def post(self, request):
        return Response({'message': 'post请求'})


class UsernameCountView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        context = {
            "username": username,
            "count": count
        }
        return Response(context)


class UserView(CreateAPIView):
    """用户注册"""
    serializer_class = serializers.CreateUserSerializer


class MyObtainJSONWebToken(ObtainJSONWebToken):
    pass


# /users/
class UserDetailView(RetrieveAPIView):
    serializer_class = serializers.UserDetaelSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# /email/
class EmailView(UpdateAPIView):
    """
    修改用户邮箱（修改用户邮箱字段）
    """
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    # 重写GenericAPIView的方法，指定要修改的是哪一条用户数据
    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    """
    激活用户邮箱
    """
    def get(self, request):
        # 1.获取请求参数： token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'})

        # 2.校验token合法性
        s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires_in=60*60*24)
        try:
            data = s.loads(token)
        except BadData:
            return Response({'message': '链接信息无效'}, status=400)
        # 3.从token中获取： user_id, email
        email = data.get('email')
        user_id = data.get('user_id')

        # 4.查询出要激活的用户对象
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return Response({'message': '激活用户不存在'}, status=400)

        # 5.修改用户对象的激活字段为true: email_active = True
        user.email_active = True
        user.save()

        # 6.响应数据： {'message': 'ok'}
        return Response({'message': 'OK'})


class BrowseHistoryView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = AddBrowseHistorySerializer

    def get(self, request):
        """查询用户浏览记录"""
        # 获取user_id
        user_id = request.user.id
        # 获取可以操作redis服务器的对象
        redis_conn = get_redis_connection('history')
        # 查询出redis中用户存储的浏览记录
        sku_ids = redis_conn.lrange('history_%s' % user_id, 0, -1)
        # 查询sku列表数据
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 调用序列化器实现输出：序列化器序列化操作
        serializer = SKUSerializer(sku_list, many=True)
        return Response(serializer.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户认证
    """
    def post(self, request, *args, **kwargs):
        # 调用父类的方法，获取drf jwt扩展默认的认证用户处理结果
        response = super().post(request, *args, **kwargs)

        # 仿照drf jwt扩展对于用户登录的认证方式，判断用户是否认证登录成功
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():     # 如果用户登录认证成功，则合并购物车
            # serializer: JSONWebTokenSerializer
            # 序列化器校验通过后返回了登录成功的user对象
            user = serializer.validated_data.get('user')
            response = merge_cart_cookie_to_redis(request, response, user)
        return response


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 10,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= 10:
            return Response({'message': '保存地址数据已达到上限'}, status=404)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=204)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=200)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)
